<template>
  <div>
    <div :class="{setButton:isActive}">
      <el-button type="primary" icon="el-icon-plus"  size="small" @click="gotolink">请假申请</el-button>
      <el-button
        size="small"
        icon="el-icon-delete-solid"
        type="danger"
        @click="batchDelete"
      >批量删除</el-button>
      <el-button type="primary" icon="el-icon-aim" size="small" @click="getSerachData">搜索</el-button>
      <el-select
        v-model="value"
        filterable
        placeholder="查询类型"
        size="small"
        clearable
        class="setSelection"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>

      <el-input
        prefix-icon="el-icon-search"
        size="small"
        placeholder="请输入查询内容"
        v-model="input"
        :class="{setInput:isActive}"
        clearable
      ></el-input>

      <el-button
        class="setExcelButton"
        type="success"
        icon="el-icon-document"
        size="small"
        @click="exportData"
      >导出表格</el-button>
      <input-excel @getResult="getMyExcelData"></input-excel>
    </div>
    <el-table
      ref="filterTable"
      :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
      style="width: 100%"
      :default-sort="{prop:'ask_Id',order:'descending'}"
      stripe
      @selection-change="selected"
      max-height="1000"
    >
      <el-table-column fixed type="selection" width="55"></el-table-column>
      <el-table-column fixed prop="userName" label="用户账号" width="100"></el-table-column>
      <el-table-column fixed prop="nickName" label="用户姓名" width="100"></el-table-column>
      <el-table-column prop="duration" sortable label="请假期限" width="150"></el-table-column>
      <el-table-column prop="status"  label="请假状态" width="150"></el-table-column>
      <el-table-column prop="reason"  label="请假原因" width="150"  :show-overflow-tooltip='true'></el-table-column>
      <el-table-column sortable v-if="false" prop="ask_Id" label="考勤id" width="150"></el-table-column>
      <el-table-column sortable v-if="false" prop="user_Id" label="用户id" width="150"></el-table-column>
      <el-table-column prop="startTime" :formatter="dateFormat" label="开始时间" width="150"></el-table-column>
      <el-table-column prop="endTime" :formatter="dateFormat" label="结束时间" width="150"></el-table-column>
      <el-table-column prop="comment" label="备注" width="120"></el-table-column>
      <el-table-column prop="recordTime" :formatter="dateFormat" label="记录时间" sortable width="150"></el-table-column>
      <el-table-column prop="updateTime" :formatter="dateFormat" label="更新时间" sortable width="150"></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)"></el-button>

          <el-button type="danger" icon="el-icon-delete" size="mini" @click="open(scope.row)"></el-button>

          <el-button
          type="warning"
            @click.native.prevent="deleteRow(scope.$index, tableData)"
            icon="el-icon-remove-outline"
            size="mini"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="currentPage"
        :page-sizes="[3,6,8,10,20,100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
      ></el-pagination>
    </div>

    <!-- 修改请假信息dialog -->
    <el-dialog title="请假信息" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="学生姓名" :label-width="formLabelWidth">
          <el-select @change="$forceUpdate()" v-model="form.userId" filterable placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="(item,index) in studentData"
              :key="index"
              :value="item.user_Id"
              :label="item.userName+'-'+item.nickName"
            ><i class="el-icon-user-solid">{{item.userName+'-'+item.nickName}}</i></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请假期限" :label-width="formLabelWidth">
          <el-input
            v-model="form.duration"
            autocomplete="off"
            prefix-icon="el-icon-date"
            :width="formLabelWidth"
            maxlength="32"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="请假时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="datetime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width:100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="请假状态" :label-width="formLabelWidth">
          <el-select
            icon="el-icon-s-flag"
            v-model="form.status"
            placeholder="请选择状态"
            :width="formLabelWidth"
            resize
            class="setDialogDateAndSex"
            clearable
          >
            <el-option label="已批阅" value="已批阅">
              <i class="el-icon-success">已批阅</i>
            </el-option>
            <el-option label="未批阅" value="未批阅">
              <i class="el-icon-error">未批阅</i>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请假原因" :label-width="formLabelWidth">
          <el-input
            v-model="form.reason"
            autocomplete="off"
            prefix-icon="el-icon-message"
            :width="formLabelWidth"
            maxlength="32"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="信息备注" :label-width="formLabelWidth">
          <el-input
            v-model="form.comment"
            autocomplete="off"
            prefix-icon="el-icon-s-comment"
            :width="formLabelWidth"
            maxlength="255"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdate">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { export2Excel } from '../../../common/js/util'
import inputExcel from '../../common/inputExcel'
import moment from 'moment'
export default {
  inject: ['reload'],
  components: { inputExcel },
  data () {
    return {
      dialogFormVisible: false,
      formLabelWidth: '120px',
      datetime: [],
      pageSize: 6,
      currentPage: 1,
      tableData: [],
      selectedCheckBox: [],
      studentData: [],
      input: '',
      isActive: true,
      addMenuFormVisible: false,
      value: '',
      options: [
        {
          value: 'userName',
          label: '用户账号:'
        },
        {
          value: 'nickName',
          label: '用户姓名:'
        },
        {
          value: 'duration',
          label: '请假期限:'
        },
        {
          value: 'status',
          label: '请假状态:'
        },
        {
          value: 'reason',
          label: '请假原因:'
        }
      ],
      columns: [
        { title: '请假ID', key: 'ask_Id' },
        { title: '用户ID', key: 'user_Id' },
        { title: '用户账号', key: 'userName' },
        { title: '用户姓名', key: 'nickName' },
        { title: '请假期限', key: 'duration' },
        { title: '开始时间', key: 'startTime' },
        { title: '结束时间', key: 'endTime' },
        { title: '请假状态', key: 'status' },
        { title: '请假原因', key: 'reason' },
        { title: '备注说明', key: 'comment' },
        { title: '创建时间', key: 'recordTime' },
        { title: '更新时间', key: 'updateTime' }
      ],
      rules: {
        attendanceTime: [
          {
            required: true,
            message: '请输入考勤时间,不能为空',
            trigger: 'blur'
          }
        ],
        attendanceStatus: [
          {
            required: true,
            message: '请选择考勤状态,不能为空',
            trigger: 'blur'
          }
        ]
      },
      form: {
        askId: '',
        userId: '',
        startTime: '',
        endTime: '',
        duration: '',
        status: '',
        reason: '',
        comment: '',
        recordTime: '',
        updateTime: ''
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      }
    }
  },
  created () {
    this.initData()
    this.getStudentData()
  },
  methods: {
    dateFormat (row, column) {
      // 修改时间格式
      var date = row[column.property]

      if (date === undefined) {
        return ''
      } else if (date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    gotolink () {
      // 点击跳转至上次浏览页面
      // this.$router.go(-1)

      // 指定跳转地址
      this.$router.replace('/askForLeavePanel')
    },
    getSerachData () {
      if (this.input === '' && this.value !== '') {
        this.$confirm('查询内容不能为空！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } else if (this.value === '' && this.input !== '') {
        this.$confirm('查询类型内容不能空！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } else if (this.value === '' && this.input === '') {
        this.initData()
      } else {
        this.$axios
          .post('/leaves/serachs', {
            json: this.value + ',' + this.input
          })
          .then(response => (this.tableData = response.data.data))
          .catch(function (error) {
            // 请求失败处理
            console.log(error)
          })
      }
    },
    getMyExcelData (data) {
      // alert(JSON.stringify(data))
      if (this.addForm != null) {
        this.$axios
          .post('/leaves/excels', {
            json: data
          })
          .then(response => {
            if (response.data.code === 200) {
              // alert(JSON.stringify(response.data));
              setTimeout(() => {
                // var obj = JSON.parse(JSON.stringify(response.data.data))
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.initData()
                this.reload()
              }, 300)
            } else {
              this.$message({
                message: '添加失败',
                type: 'warning'
              })
              this.reload()
            }
          })
          .catch(function (error) {
            // 请求失败处理
            console.log(error)
          })
      }
      console.log(data)
    },
    exportData () {
      // Excel导出数据
      export2Excel(this.columns, this.tableData)
    },
    onSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleAdd()
          console.log('success submit!!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    selected: function (value) {
      // 复选框获取已经被选择的记录
      this.selectedCheckBox = value
    },
    batchDelete: function () {
      // 获取所有选中行的id组成的字符串，以逗号分隔
      var ids = this.selectedCheckBox.map(item => item.ask_Id).join()

      console.log(ids)
      // 批量删除操作方法
      this.$confirm('此操作将批量删除已选择记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.handleDeleteUsersByIds(ids)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleDeleteUsersByIds: function (array) {
      // 删除操作方法
      // alert(index.userId);
      this.$axios
        .post('/leaves/dels', {
          Ids: array
        })
        .then(response => {
          if (response.data.code === 200) {
            setTimeout(() => {
              this.reload()
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.initData()
            }, 300)
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        })
        .catch(failResponse => {
          this.$message({
            message: '请求失败',
            type: 'warning'
          })
        })
    },
    handleSizeChange (val) {
      this.currentPage = 1
      this.pageSize = val
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange (val) {
      this.currentPage = val
      console.log(`当前页: ${val}`)
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    open (index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // alert(index.userId);
          this.handleDelete(index.ask_Id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleEdit: function (rows) {
      // 打开修改操作dialog方法
      this.dialogFormVisible = true // 打开dialog
      this.form = rows // 获取权限信息
      this.form.userId = rows.user_Id
      this.form.askId = rows.ask_Id
      this.datetime[0] = this.form.startTime
      this.datetime[1] = this.form.endTime
      console.log(rows)
    },
    handleUpdate: function () {
      this.form.startTime = this.datetime[0]
      this.form.endTime = this.datetime[1]
      // 执行更新操作方法
      this.dialogFormVisible = false
      if (this.form != null) {
        this.$axios
          .put('/leaves', {
            json: this.form
          })
          .then(response => {
            if (response.data.code === 200) {
              setTimeout(() => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })

                this.initData()
              }, 300)
            } else {
              this.$message({
                message: '修改失败',
                type: 'warning'
              })
            }
          })
          .catch(function (error) {
            // 请求失败处理
            console.log(error)
          })
      }
      // alert(this.form.toString);
    },
    handleDelete: function (index) {
      // 删除操作方法
      // alert(index.userId);
      this.$axios
        .delete('/leaves/' + index)
        .then(response => {
          if (response.data.code === 200) {
            setTimeout(() => {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.initData()
            }, 300)
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        })
        .catch(failResponse => {
          this.$message({
            message: '请求失败',
            type: 'warning'
          })
        })
    },
    getStudentData () {
      // 获取学生信息
      this.$axios
        .get('/leaves/studentInfos')
        .then(response => (this.studentData = response.data.data))
        .catch(function (error) {
          // 请求失败处理
          console.log(error)
        })
    },
    initData () {
      // 初始化数据
      this.$axios
        .get('/leaves/studentAndAskForLeaveInfos')
        .then(response => (this.tableData = response.data.data))
        .catch(function (error) {
          // 请求失败处理
          console.log(error)
        })
    }
  }
}
</script>
<style scoped>
.setInput {
  width: 200px;
}
.setButton {
  text-align: left;
  margin-left: 0%;
  height: 60px;
}
.setSelection {
  width: 100px;
  background-color: dodgerblue;
}
.setExcelButton {
  margin-left: 5%;
}
.setDialogDateAndSex {
  width: 470px;
}
</style>
